package migration

import (
	"fmt"
	"time"

	// "GinAdmin/internal/db"
	// "GinAdmin/internal/model"
	"GinAdmin/core/database"
	"GinAdmin/model"

	"gorm.io/gorm"
)

// AutoMigrate 自动迁移数据表结构
func AutoMigrate(db *gorm.DB) error {
	// 迁移表结构
	err := db.AutoMigrate(
		&model.User{},
		&model.Role{},
		&model.Department{},
		&model.Menu{},
		&model.Setting{},
		&model.Message{},
	)
	if err != nil {
		return err
	}

	// 初始化基础数据
	if err := initAdminUser(db); err != nil {
		return err
	}

	if err := initRoles(db); err != nil {
		return err
	}

	if err := initMenus(db); err != nil {
		return err
	}

	if err := initSettings(db); err != nil {
		return err
	}

	return nil
}

// 初始化管理员用户
func initAdminUser(db *gorm.DB) error {
	var count int64
	db.Model(&model.User{}).Count(&count)
	if count > 0 {
		return nil
	}

	// 加密密码
	hashedPassword, err := model.EncryptPassword("123456")
	if err != nil {
		return err
	}

	adminUser := model.User{
		Username:  "admin",
		Password:  hashedPassword,
		RealName:  "系统管理员",
		Mobile:    "13800138000",
		Email:     "admin@example.com",
		Avatar:    "https://avatars.githubusercontent.com/u/1?v=4",
		Status:    1,
		LastLogin: time.Now(),
	}

	if err := db.Create(&adminUser).Error; err != nil {
		return err
	}

	// 创建默认角色
	adminRole := model.Role{
		Name:   "超级管理员",
		Code:   "admin",
		Status: 1,
		Remark: "系统超级管理员",
	}

	if err := db.Create(&adminRole).Error; err != nil {
		return err
	}

	// 用户角色关联
	if err := db.Exec("INSERT INTO go_user_role (user_id, role_id) VALUES (?, ?)", adminUser.ID, adminRole.ID).Error; err != nil {
		return err
	}

	fmt.Println("初始化管理员用户成功")
	return nil
}

// 初始化角色
func initRoles(db *gorm.DB) error {
	var count int64
	db.Model(&model.Role{}).Count(&count)
	if count > 1 {
		return nil
	}

	roles := []model.Role{
		{
			Name:   "普通用户",
			Code:   "user",
			Status: 1,
			Remark: "普通用户角色",
		},
		{
			Name:   "访客",
			Code:   "guest",
			Status: 1,
			Remark: "访客角色",
		},
	}

	for _, role := range roles {
		if err := db.Create(&role).Error; err != nil {
			return err
		}
	}

	fmt.Println("初始化角色成功")
	return nil
}

// 初始化菜单
func initMenus(db *gorm.DB) error {
	var count int64
	db.Model(&model.Menu{}).Count(&count)
	if count > 0 {
		return nil
	}

	menus := []model.Menu{
		{
			Title:      "仪表盘",
			Name:       "dashboard",
			ParentID:   0,
			Path:       "/dashboard",
			Component:  "dashboard/index",
			Icon:       "dashboard",
			Sort:       1,
			Hidden:     false,
			Status:     1,
			Permission: "dashboard",
		},
		{
			Title:      "系统管理",
			Name:       "system",
			ParentID:   0,
			Path:       "/system",
			Component:  "Layout",
			Icon:       "setting",
			Sort:       2,
			Hidden:     false,
			Status:     1,
			Permission: "system",
		},
		{
			Title:      "用户管理",
			Name:       "user",
			ParentID:   2,
			Path:       "/system/user",
			Component:  "system/user/index",
			Icon:       "user",
			Sort:       1,
			Hidden:     false,
			Status:     1,
			Permission: "system:user:list",
		},
		{
			Title:      "角色管理",
			Name:       "role",
			ParentID:   2,
			Path:       "/system/role",
			Component:  "system/role/index",
			Icon:       "peoples",
			Sort:       2,
			Hidden:     false,
			Status:     1,
			Permission: "system:role:list",
		},
		{
			Title:      "菜单管理",
			Name:       "menu",
			ParentID:   2,
			Path:       "/system/menu",
			Component:  "system/menu/index",
			Icon:       "tree-table",
			Sort:       3,
			Hidden:     false,
			Status:     1,
			Permission: "system:menu:list",
		},
	}

	for i := range menus {
		if err := db.Create(&menus[i]).Error; err != nil {
			return err
		}
	}

	// 给超级管理员角色分配所有菜单
	var adminRole model.Role
	if err := db.Where("code = ?", "admin").First(&adminRole).Error; err != nil {
		return err
	}

	var allMenus []model.Menu
	if err := db.Find(&allMenus).Error; err != nil {
		return err
	}

	for _, menu := range allMenus {
		if err := db.Exec("INSERT INTO go_role_menu (role_id, menu_id) VALUES (?, ?)", adminRole.ID, menu.ID).Error; err != nil {
			return err
		}
	}

	fmt.Println("初始化菜单成功")
	return nil
}

// 初始化系统设置
func initSettings(db *gorm.DB) error {
	var count int64
	db.Model(&model.Setting{}).Count(&count)
	if count > 0 {
		return nil
	}

	settings := []model.Setting{
		{
			Key:    "site_name",
			Value:  "GinAdmin管理系统",
			Group:  "system",
			Remark: "站点名称",
			Type:   "string",
		},
		{
			Key:    "site_description",
			Value:  "基于Gin+Vue的管理系统框架",
			Group:  "system",
			Remark: "站点描述",
			Type:   "string",
		},
		{
			Key:    "site_logo",
			Value:  "/static/logo.png",
			Group:  "system",
			Remark: "站点Logo",
			Type:   "string",
		},
		{
			Key:    "backend_theme",
			Value:  "light",
			Group:  "system",
			Remark: "后台主题",
			Type:   "string",
		},
	}

	for _, setting := range settings {
		if err := db.Create(&setting).Error; err != nil {
			return err
		}
	}

	fmt.Println("初始化系统设置成功")
	return nil
}

// RunMigration 执行数据库迁移
func RunMigration() error {
	// 获取数据库连接
	// DB := db.DB
	DB := database.DB
	if DB == nil {
		return fmt.Errorf("数据库连接未初始化")
	}

	// 自动迁移表结构
	return AutoMigrate(DB)
}
